//
//  MessageInputView.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/29.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "MessageInputView.h"
#import "ANGradientButton.h"
#import "IMMoreFunctionView.h"
#import "FINEmojiKeyBoardView.h"

#define kTextViewHeight 36.0f
#define kMaxHeight 113.0f
#define kMoreViewHeight 216.0f

typedef enum : NSUInteger {
    MessageInputViewStateNormal, // 初始状态
    MessageInputViewStateMore, // 显示更多功能视图
    MessageInputViewStateEmoji, // 显示表情
    MessageInputViewStateKeyboard, // 显示键盘
} MessageInputViewState;

@interface MessageInputView ()<UITextViewDelegate,FINEmojiKeyboardViewDataSource,FINEmojiKeyboardViewDelegate>

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIButton *moreButton;
@property (nonatomic, strong) UIButton *emojiButton;
@property (nonatomic, strong) IMMoreFunctionView *moreView;
@property (nonatomic, strong) FINEmojiKeyboardView *emojiView;

@property (nonatomic, assign) CGFloat currentKeyboardHeight;

@property (nonatomic) MessageInputViewState state;

@end

@implementation MessageInputView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        frame.size.height = kTextViewHeight + kMoreViewHeight + 20 + kiPhoneXInsetBottom;
        self.frame = frame;
        self.state = MessageInputViewStateNormal;
    }
    return self;
}

- (void)setupSubViews
{
    self.backgroundColor = [UIColor whiteColor];
    
    self.textView = [[UITextView alloc] init];
    self.textView.scrollEnabled = NO;
    self.textView.layer.borderWidth = 1;
    self.textView.layer.borderColor = kColorDDD.CGColor;
    self.textView.layer.cornerRadius = 4;
    self.textView.layer.masksToBounds = YES;
    self.textView.font = [UIFont systemFontOfSize:16];
    self.textView.returnKeyType = UIReturnKeySend;
    self.textView.delegate = self;
    [self addSubview:self.textView];
    
    self.moreButton = [[UIButton alloc] init];
    [self.moreButton setImage:[UIImage imageNamed:@"tianjia_n"] forState:UIControlStateNormal];
    [self.moreButton setImage:[UIImage imageNamed:@"tianjia_h"] forState:UIControlStateHighlighted];
    self.moreButton.tag = 0;
    [self addSubview:self.moreButton];
    [self.moreButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.emojiButton = [[UIButton alloc] init];
    [self.emojiButton setImage:[UIImage imageNamed:@"emoji_n"] forState:UIControlStateNormal];
    [self.emojiButton setImage:[UIImage imageNamed:@"emoji_h"] forState:UIControlStateHighlighted];
    self.emojiButton.tag = 0;
    [self addSubview:self.emojiButton];
    [self.emojiButton addTarget:self action:@selector(emojiAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.moreView = [[IMMoreFunctionView alloc] init];
    self.moreView.backgroundColor = kColorF2F2F2;
//    self.moreView.alpha = 0;
    [self addSubview:self.moreView];
    
    self.emojiView = [[FINEmojiKeyboardView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds)+kiPhoneXInsetBottom, kScreenW, kMoreViewHeight) dataSource:self];
    self.emojiView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.emojiView.delegate = self;
    self.emojiView.backgroundColor = kColorF2F2F2;
//    self.emojiView.alpha = 0;
    [self addSubview:self.emojiView];
    
    WeakSelf
    self.moreView.didSelectedPhotoHandle = ^{
        if ([weakSelf.delegate respondsToSelector:@selector(moreFunctionDidSelectedPhoto)]) {
            [weakSelf.delegate moreFunctionDidSelectedPhoto];
        }
    };
    
    // 添加通知监听见键盘弹出/退出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)updateEmojiButton
{
    if (self.emojiButton.tag%2 == 0) {
        [self.emojiButton setImage:[UIImage imageNamed:@"emoji_n"] forState:UIControlStateNormal];
        [self.emojiButton setImage:[UIImage imageNamed:@"emoji_h"] forState:UIControlStateHighlighted];
    }
    else {
        [self.emojiButton setImage:[UIImage imageNamed:@"keyboard_n"] forState:UIControlStateNormal];
        [self.emojiButton setImage:[UIImage imageNamed:@"keyboard_h"] forState:UIControlStateHighlighted];
    }
}

- (void)setState:(MessageInputViewState)state
{
    _state = state;
    switch (state) {
        case MessageInputViewStateNormal:
            self.moreButton.tag = 0;
            self.emojiButton.tag = 0;
            break;
        case MessageInputViewStateMore:
            self.emojiButton.tag = 0;
            break;
        case MessageInputViewStateEmoji:
            self.moreButton.tag = 0;
            break;
        case MessageInputViewStateKeyboard:
            self.moreButton.tag = 0;
            self.emojiButton.tag = 0;
            break;
            
        default:
            break;
    }
    [self updateEmojiButton];
}

- (void)moreAction
{
    self.moreButton.tag += 1;
    if ([self.delegate respondsToSelector:@selector(clickMoreFunction:)]) {
        [self.delegate clickMoreFunction:(self.moreButton.tag%2)];
    }
}

- (void)emojiAction
{
    self.emojiButton.tag += 1;
    if ([self.delegate respondsToSelector:@selector(clickEmojiFunction:)]) {
        [self.delegate clickEmojiFunction:(self.emojiButton.tag%2)];
    }
}

// 键盘监听事件
- (void)keyboardAction:(NSNotification*)sender{
    // 通过通知对象获取键盘frame: [value CGRectValue]
    NSDictionary *useInfo = [sender userInfo];
    NSValue *value = [useInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    if([sender.name isEqualToString:UIKeyboardWillShowNotification]){
        self.currentKeyboardHeight = [value CGRectValue].size.height;
        self.state = MessageInputViewStateKeyboard;
//        if ([self.delegate respondsToSelector:@selector(keyboardWillShow:)]) {
//            [self.delegate keyboardWillShow:self.currentKeyboardHeight];
//        }
    }
    else {
        self.currentKeyboardHeight = 0;
//        if ([self.delegate respondsToSelector:@selector(keyboardWillDismiss)]) {
//            [self.delegate keyboardWillDismiss];
//        }
    }
//    self.moreButton.tag = 0;
//    self.emojiButton.tag = 0;
    [self changeFrame];
}

- (void)setupConstraints
{
    CGFloat moreWidth = 28;
    CGFloat emojiWidth = 28;
    CGFloat margin = 15;
    self.textView.frame = CGRectMake(15, 10, CGRectGetWidth(self.frame)-15-moreWidth-emojiWidth-margin*2-15, kTextViewHeight);
    self.emojiButton.frame = CGRectMake(CGRectGetMaxX(self.textView.frame)+margin, CGRectGetMidY(self.textView.frame)-emojiWidth/2, emojiWidth, emojiWidth);
    self.moreButton.frame = CGRectMake(CGRectGetWidth(self.frame)-15-moreWidth, CGRectGetMinY(self.emojiButton.frame), moreWidth, moreWidth);
    self.moreView.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame)+10+kiPhoneXInsetBottom, kScreenW, kMoreViewHeight);
//    self.emojiView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), kScreenW, kMoreViewHeight);
}

- (void)hideAll
{
    if (self.state == MessageInputViewStateNormal) {
        return;
    }
    self.state = MessageInputViewStateNormal;
    [self.textView endEditing:YES];
    [self changeFrame];
    [UIView animateWithDuration:0.3 animations:^{
        self.emojiView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), kScreenW, kMoreViewHeight);
    }];
}

- (void)showMoreFunctionView
{
    self.state = MessageInputViewStateMore;
    self.moreView.alpha = 1;
    [self.textView endEditing:YES];
    CGRect frame = self.frame;
    frame.size.height = kTextViewHeight + kMoreViewHeight + 20 + kiPhoneXInsetBottom;
    self.frame = frame;
    frame.origin.y = kScreenH-kStatusAndNavBarHeight-frame.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = frame;
        self.emojiView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), kScreenW, kMoreViewHeight);
        self.moreView.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame)+10, kScreenW, kMoreViewHeight);
    }];
    
    if ([self.delegate respondsToSelector:@selector(messageInputViewDidChange:)]) {
        [self.delegate messageInputViewDidChange:self.frame.origin.y];
    }
}

- (void)showKeyboard
{
    self.state = MessageInputViewStateKeyboard;
    [self.textView becomeFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        self.emojiView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), kScreenW, kMoreViewHeight);
    }];
}

- (void)showEmojiView
{
    self.state = MessageInputViewStateEmoji;
    self.emojiView.alpha = 1;
    [self.textView endEditing:YES];
    CGRect frame = self.frame;
    frame.size.height = kTextViewHeight + kMoreViewHeight + 20 + kiPhoneXInsetBottom;
    self.frame = frame;
    frame.origin.y = kScreenH-kStatusAndNavBarHeight-frame.size.height;
    self.moreView.alpha = 0;
    self.moreView.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame)+10+kiPhoneXInsetBottom, kScreenW, kMoreViewHeight);
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = frame;
        self.emojiView.frame = CGRectMake(0, CGRectGetMinY(self.moreView.frame)-kiPhoneXInsetBottom, kScreenW, kMoreViewHeight);
    }];
    
    if ([self.delegate respondsToSelector:@selector(messageInputViewDidChange:)]) {
        [self.delegate messageInputViewDidChange:self.frame.origin.y];
    }
}

- (void)changeFrame
{
    CGFloat height = ceilf([self.textView sizeThatFits:CGSizeMake(self.textView.frame.size.width, MAXFLOAT)].height);
    if (height >= kMaxHeight) {
        height = kMaxHeight;
        self.textView.scrollEnabled = YES;
    }
    else {
        self.textView.scrollEnabled = NO;
    }
    CGRect frame = self.textView.frame;
    frame.size.height = height;
    self.textView.frame = frame;
    self.moreView.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame)+10+kiPhoneXInsetBottom, kScreenW, kMoreViewHeight);
    frame = self.frame;
    if (self.state == MessageInputViewStateNormal) {
        frame.origin.y = kScreenH-kStatusAndNavBarHeight-kiPhoneXInsetBottom-self.currentKeyboardHeight-height-20;
    }
    else if (self.state == MessageInputViewStateKeyboard) {
        frame.origin.y = kScreenH-kStatusAndNavBarHeight-self.currentKeyboardHeight-height-20;
    }
    else {
        frame.origin.y = kScreenH-kStatusAndNavBarHeight-kMoreViewHeight-height-20;
    }
    self.frame = frame;
    if (self.state == MessageInputViewStateEmoji) {
        self.emojiView.frame = CGRectMake(0, CGRectGetMinY(self.moreView.frame), kScreenW, kMoreViewHeight);
    }
    else {
        self.emojiView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), kScreenW, kMoreViewHeight);
    }
    if ([self.delegate respondsToSelector:@selector(messageInputViewDidChange:)]) {
        [self.delegate messageInputViewDidChange:self.frame.origin.y];
    }
    
//    self.senderBtn.enabled = self.textView.text.length > 0;
}

#pragma mark - FINEmojiKeyboardViewDataSource

- (UIImage *)emojiKeyboardView:(FINEmojiKeyboardView *)emojiKeyboardView imageForSelectedCategory:(FINEmojiKeyboardViewCategoryImage)category {
    UIImage *selectedIamge;
    switch (category) {
        case FINEmojiKeyboardViewCategoryImageRecent:
            selectedIamge = [UIImage imageNamed:@"emoji-recent-h"];
            break;
        case FINEmojiKeyboardViewCategoryImageFace:
            selectedIamge = [UIImage imageNamed:@"emoji-face-h"];
            break;
        case FINEmojiKeyboardViewCategoryImageBell:
            selectedIamge = [UIImage imageNamed:@"emoji-balloon-h"];
            break;
        case FINEmojiKeyboardViewCategoryImageFlower:
            selectedIamge = [UIImage imageNamed:@"emoji-bear-h"];
            break;
        case FINEmojiKeyboardViewCategoryImageCar:
            selectedIamge = [UIImage imageNamed:@"emoji-car-h"];
            break;
        case FINEmojiKeyboardViewCategoryImageCharacters:
            selectedIamge = [UIImage imageNamed:@"emoji-symbol-h"];
            break;
        default:
            break;
    }
    return selectedIamge;
}

- (UIImage *)emojiKeyboardView:(FINEmojiKeyboardView *)emojiKeyboardView imageForNonSelectedCategory:(FINEmojiKeyboardViewCategoryImage)category {
    UIImage *noneSelectedIamge;
    switch (category) {
        case FINEmojiKeyboardViewCategoryImageRecent:
            noneSelectedIamge = [UIImage imageNamed:@"emoji-recent-n"];
            break;
        case FINEmojiKeyboardViewCategoryImageFace:
            noneSelectedIamge = [UIImage imageNamed:@"emoji-face-n"];
            break;
        case FINEmojiKeyboardViewCategoryImageBell:
            noneSelectedIamge = [UIImage imageNamed:@"emoji-balloon-n"];
            break;
        case FINEmojiKeyboardViewCategoryImageFlower:
            noneSelectedIamge = [UIImage imageNamed:@"emoji-bear-n"];
            break;
        case FINEmojiKeyboardViewCategoryImageCar:
            noneSelectedIamge = [UIImage imageNamed:@"emoji-car-n"];
            break;
        case FINEmojiKeyboardViewCategoryImageCharacters:
            noneSelectedIamge = [UIImage imageNamed:@"emoji-symbol-n"];
            break;
        default:
            break;
    }
    return noneSelectedIamge;
}

- (UIImage *)backSpaceButtonImageForEmojiKeyboardView:(FINEmojiKeyboardView *)emojiKeyboardView {
    return nil;
}

- (void)emojiKeyBoardView:(FINEmojiKeyboardView *)emojiKeyBoardView didUseEmoji:(NSString *)emoji {
    
    NSMutableString *text = self.textView.text.mutableCopy;
    [text appendString:emoji];
    self.textView.text = text;
    [self changeFrame];
}

- (void)emojiKeyBoardViewDidPressBackSpace:(FINEmojiKeyboardView *)emojiKeyBoardView {
    [self.textView deleteBackward];
}

- (void)emojiKeyBoardViewDidPressSend:(FINEmojiKeyboardView *)emojiKeyBoardView {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.textView.text.length > 0) {
                if ([self.delegate respondsToSelector:@selector(sendMessage:)]) {
                    [self.delegate sendMessage:self.textView.text];
                }
                self.textView.text = @"";
                [self changeFrame];
            }
        });
    });
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [self changeFrame];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        if (textView.text.length > 0) {
            if ([self.delegate respondsToSelector:@selector(sendMessage:)]) {
                [self.delegate sendMessage:self.textView.text];
            }
            self.textView.text = @"";
            [self changeFrame];
        }
        return NO;
    }
    return YES;
}

@end
